<script type="text/javascript" charset="utf-8" src="__STATIC_JS__/jquery-2.1.3.min.js"> </script>
<link rel="stylesheet" href="__STATIC_JS__croppic/croppic.css">
<script type="text/javascript" charset="utf-8" src="__STATIC_JS__croppic/croppic.js"> </script>
<script type="text/javascript" charset="utf-8" src="__STATIC_JS__ddsort/ddsort.js"> </script>

<style>
    #container{
        padding: 0px;
        border-radius:0px;
        border-width:0px;
    }
    #img_preview{
        display: inline;
        float: left;
        margin-top: 40px;
        overflow: hidden;
    }
    .imgdiv{
        display: inline;
        float: left;
        text-align: center;
        border: 1px solid #ccc;
        padding: 5px;
        padding-bottom: 0;
        margin-right: 10px;
    }
    #operate{
    	margin-top: 5px;
    }
    #operate a{
     	cursor:pointer
    }
    #operate a:hover{
    	color: #009688;
    }
    .layui-btn{
    	margin-top: 10px;
    }
    .grade_price{
        width: 80% !important;
        float: left;
        display: inline;
    }
    .grade_price input{
        display: inline;
        width: 190px;;
    }
    .goods-stock{
        width: 80px;
        display: inline;
    }
    .spec-item .layui-form-checkbox{
        margin-top: 0 !important;
    }
    .new-spec{
        display: inline-block;
        width: 100px;
    }

    .extend-goods-cat{
        width: 86% !important;
    }
    .extend-goods-cat>.layui-btn{
        margin-top: 3px;
        margin-right: 5px;
    }
    .extend-goods-cat>.layui-btn,.extend-goods-cat>.layui-form-select{
        float: left;;
    }

    #add_extend_cat{
        /*display: none;*/
        float: left;
    }
    #add_extend_cat>.layui-form-select{
        float: left;
        margin-right: 5px;;
    }
    #add_extend_cat>.layui-form-select .layui-edge{
        margin-top: -8px;
    }
    #fixed-block{
        position: fixed;
        width: 100%;
        bottom: 0px;
        left:0px;
        z-index: 99999;
        background: #eeeeee;
        /*padding-left:40px;*/
        padding-bottom:5px;
        text-align: center;
    }

</style>
<form class="layui-form seller-alone-form" action="{:url('goods/doEdit')}" method="post"   lay-filter="goodsForm" style="padding-bottom: 58px;">
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;"> <legend>基础信息</legend></fieldset>
    <div class="layui-form-item">
        <label class="layui-form-label"> <i class="required-color">*</i>商品分类：</label>
        <div class="layui-input-inline">
            <select name="goods_cat_id">
                <option>请选择</option>
                {volist name="goodsCatTree" id="vo"}
                <option value="{$vo.id}" {if condition="$data.goods_cat_id eq $vo.id"}selected {/if} >{$vo.name}</option>
                {/volist}
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">扩展分类：</label>
        <div class="layui-input-inline extend-goods-cat">
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm add-extend-goods-cat" >添加</button>
            <div id="add_extend_cat">
                {if condition="count($extendsCat)>0"}
                {volist name="extendsCat" id="cat"}
                    <select name="goods_cat_extend_id[]">
                        <option>请选择</option>
                        {volist name="goodsCatTree" id="vo"}
                        <option value="{$vo.id}" {if condition="$cat.goods_cat_id eq $vo.id"}selected {/if} >{$vo.name}</option>
                        {/volist}
                    </select>
                {/volist}
                {/if}
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"><i class="required-color">*</i>商品类型：</label>
        <div class="layui-input-inline">
            <select name="goods_type_id" id="goods_type_id" lay-filter="goods_type_id">
                <option value="">请选择类型</option>
                {if condition="count($typeList)>0"}
                    {volist name="typeList" id="vo"}
                        <option value="{$vo.id}" {if condition="$vo.id eq $data.goods_type_id"} selected{/if}>{$vo.name}</option>
                    {/volist}
                {/if}
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"><i class="required-color">*</i>商品名称：</label>
        <div class="layui-input-inline">
            <input type="text" name="goods[name]" value="{$data.name}" lay-verify="title" autocomplete="off" placeholder="请输入商品名称" class="layui-input">
            <input type="hidden" name="goods[id]" id="goods_id" value="{$data.id}">

        </div>
        <div class="layui-form-mid layui-word-aux">最多可输入200个汉字</div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品编号：</label>
        <div class="layui-input-inline">
            <input type="text" name="goods[bn]" value="{$data.bn}"  lay-verify="title" autocomplete="off" placeholder="请输入商品编号" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品品牌：</label>
        <div class="layui-input-inline">
            <select name="goods[brand_id]">
                <option value="">请选择品牌</option>
                {if condition="count($brandList)>0"}
                {volist name="brandList" id="vo"}
                <option value="{$vo.id}" {if condition="$vo.id eq $data.brand_id"} selected {/if}>{$vo.name}</option>
                {/volist}
                {/if}
            </select>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">商品简介：</label>
        <div class="layui-input-block">
            <textarea placeholder="请输入商品简介" name="goods[brief]" class="layui-textarea">{$data.brief}</textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"><i class="required-color">*</i>商品图片：</label>

        <div class="layui-upload" id="imgs">
            <button type="button" class="layui-btn" id="goods_img" onclick="upImage()">上传图片</button>
            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                <p>预览图：[第一张图片为默认图，可拖动图片进行排序]</p>
                <div class="layui-upload-list" id="img_preview">
                    {volist name="data['images']" id="image"}
                    <div class="imgdiv">
                        <img src="{$image.image_path}"  class="layui-upload-img" style="width: 100px;height:100px;">
                        <div id="operate">
                            <div><a class="del" onclick="delImg(this,'{$image.image_id}')">删除</a>|<a class="setmain" onclick="setDefault(this,'{$image.image_id}')">设为主图</a>|<a class="croppic" data-id="{$image.image_id}" onclick="croppic(this,'{$image.image_path }')">裁剪</a></div>
                        </div>
                        <input type='hidden' name='goods[img][]' value="{$image.image_id}">
                    </div>
                    {/volist}
                </div>
            </blockquote>
        </div>
    </div>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;"><legend>销售信息</legend></fieldset>
    <div id="product-info">
    {php}echo $spec_html;{/php}
    </div>

    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;"> <legend>商品详情</legend></fieldset>
    {:hook('editgoodsview',['id'=>$data.id])}
    <div class="layui-form-item">
        <label class="layui-form-label">会员价：</label>
        <div class="layui-input-inline grade_price">
            {volist name="gradelist" id="vo"}
            {$vo.name}：<input type="text" name="goods[grade_price][{$vo.id}]" lay-verify="title" autocomplete="off" placeholder="会员优惠" value="{$vo.grade_price}" class="layui-input">
            {/volist}
        </div>
        <div class="layui-form-mid layui-word-aux" style="margin-left: 110px;">
            会员价为0时，使用默认价格。大于0时，商品实际价格为商品价格减去会员价
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">重量：</label>
        <div class="layui-input-inline">
            <input type="text" name="goods[weight]" value="{$data.weight}" lay-verify="title" autocomplete="off" placeholder="请输入商品重量，单位（克）" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">单位：</label>
        <div class="layui-input-inline">
            <input type="text" name="goods[unit]" value="{$data.unit}" lay-verify="title" autocomplete="off" placeholder="请输入商品单位" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item" pane>
        <label class="layui-form-label">上架：</label>
        <div class="layui-input-block">
            <input type="checkbox" {if condition="$data.marketable eq 1"} checked="" {/if} value="1" name="goods[marketable]" lay-skin="switch" lay-filter="switchTest" title="开关"><div class="layui-unselect layui-form-switch layui-form-onswitch" lay-skin="_switch"><em></em><i></i></div>
        </div>
    </div>
    <div class="layui-form-item" pane>
        <label class="layui-form-label">推荐：</label>
        <div class="layui-input-block">
            <input type="checkbox" value="1"  {if condition="$data.is_recommend eq 1"} checked="true" {/if} name="goods[is_recommend]" lay-skin="switch" lay-filter="switchTest" title="开关"><div class="layui-unselect layui-form-switch layui-form-onswitch" lay-skin="_switch"><em></em><i></i></div>
        </div>
    </div>
    <div class="layui-form-item" pane>
        <label class="layui-form-label">热门：</label>
        <div class="layui-input-block">
            <input type="checkbox"  value="1" name="goods[is_hot]" {if condition="$data.is_hot eq 1"} checked="" {/if} lay-skin="switch" lay-filter="switchTest" title="开关"><div class="layui-unselect layui-form-switch layui-form-onswitch" lay-skin="_switch"><em></em><i></i></div>
        </div>
    </div>
    <div class="layui-form-item layui-form-text" >
        <label class="layui-form-label">详细介绍：：</label>
        <div id="goods_intro" style="display: none;">{$data.intro}</div>
    </div>
    <div class="layui-form-item" >
        <script id="container" name="goods[intro]" type="text/plain" class="layui-textarea"></script>
    </div>

    <div class="layui-form-item" id="fixed-block">
        <div >
            <input type="hidden" name="open_spec" value="{$open_spec}" id="open_spec_value">
            {:zbToken()}
            <button class="layui-btn" lay-submit="" lay-filter="save">保存</button>
            <a href="javascript:history.back(-1);" class="layui-btn layui-btn-primary">返回</a>
        </div>
    </div>
</form>

<div style="display: none">
    <select name="goods_cat_extend_id[]" id="goods_cat_extend_id">
        <option>请选择</option>
        {volist name="goodsCatTree" id="vo"}
        <option value="{$vo.id}">{$vo.name}</option>
        {/volist}
    </select>
</div>

<script id="image_tpl" type="text/html">
    {{# layui.each(d, function(index, item){  }}
    <div class="imgdiv">
        <img src="{{ item.src }}"  class="layui-upload-img" style="width: 100px;height:100px;">
        <div id="operate">
            <div><a class="del" onclick="delImg(this,'{{ item.image_id }}')">删除</a>|<a class="setmain" onclick="setDefault(this,'{{ item.image_id }}')">设为主图</a>|<a class="croppic" data-id="{{ item.image_id }}" onclick="croppic(this,'{{ item.src }}')">裁剪</a></div>
        </div>
        <input type='hidden' name='goods[img][]' value="{{ item.image_id }}">
    </div>
    {{#  }); }}
</script>



<script type="text/javascript">
    var ue = UE.getEditor('container');
    var intro=$("#goods_intro").text();

    ue.ready(function(){
        ue.setContent(intro);
    })
</script>
<script>
    //渲染表单
    var laytpl = '';
    layui.use(['form','laytpl','upload'], function(){
        var $ = layui.jquery
                ,upload = layui.upload;
        var form = layui.form;
            laytpl = layui.laytpl;

        form.render();
        //保存商品
        form.on('submit(save)', function(data){
            formData = data.field;
            if(!formData){
                layer.msg('请先完善数据', {time: 1300});
                return false;
            }
            JsPost('{:url("Goods/doEdit")}',formData,function(e){
                if(e.status === true){
                    layer.msg(e.msg, {time: 1300}, function(){
                        window.location.href='{:url("Goods/index")}';
                    });
                }else{
                    layer.msg(e.msg, {time: 1300});
                }
            });
            return false;
        });
        var defaultTypeId = parseInt('{$data.goods_type_id}');

        //商品分类联动商品类型
        form.on('select', function (data) {
            var obj = data.elem;
            var type = $(obj).attr('lay-filter');
            var value = data.value;
            if (type == 'goods_cat_id' && value) {
                JsPost('{:url("Categories/getInfo")}', {id: value}, function (res) {
                    if (res.status) {
                        if (res.data.type_id && res.data.type_id != defaultTypeId) {
                            JsPost('{:url("Goods/getSpec")}', {'type_id': res.data.type_id}, function (e) {
                                if (e.status === true) {
                                    form.val("goodsForm", {
                                        "goods_type_id": res.data.type_id
                                    })
                                    defaultTypeId = res.data.type_id;
                                    $("#product-info").html(e.data);
                                }
                            });
                        }
                    } else {
                        layer.msg(res.msg);
                    }
                });
            }
        });

        form.on('select(goods_type_id)', function (data) {
            var type_id = data.value;
            if (type_id) {
                $("#open_spec_value").val('');//重置是否开启多规格
                layer.confirm('更换类型后，货品需重新生成，确定要更换吗？', {
                    btn: ['确定', '取消']
                    , title: '提示',
                }, function (index) {
                    layer.close(index);
                    defaultTypeId = type_id;
                    JsPost('{:url("Goods/getSpec")}', {'type_id': type_id}, function(e){
                        if (e.status === true) {
                            $("#product-info").html(e.data);
                        } else {
                            layer.msg(e.msg);
                        }
                    });
                }, function () {
                });
            }
        });

        /**
         * 添加扩展分类
         */
        $(document).on('click', '.add-extend-goods-cat', function(){
            $("#add_extend_cat").show();
            var newCat = $("#goods_cat_extend_id").clone();
            $("#add_extend_cat").append(newCat);
            form.render();
        })


    });

    $("body").on("click", "#open_spec", function () {
        var is_open = $(this).attr("is_open");
        if (is_open == 'false') {
            $("input[name=open_spec]").val("1");
            $("#spec_select").show();
            $("#no_spec").hide();
            $(this).html("取消规格");
            $(this).attr("is_open", "true");
        } else {
            $("input[name=open_spec]").val("0");
            $("#spec_select").hide();
            $("#no_spec").show();
            $(this).html("开启");
            $(this).attr("is_open", "false");
            $("#more_spec input").val('');
        }
    });


    $("body").on("click", ".generate-spec", function () {
        var list = $('#spec_select input[type=checkbox]:checked');
        if (list.length > 0) {
            var data = $("#spec_form input").serialize();
            data = data+'&goods_id='+$("#goods_id").val();
            JsPost('{:url("Goods/getSpecHtml")}', data, function(e){
                if (e.status === true) {
                    $("#more_spec").html(e.data);
                } else {
                    layer.msg(e.msg);
                }
            });
        } else {
            layer.msg("请选择属性");
            return false;
        }
        return false;
    });
    //删除行规格
    $("body").on("click", ".del-class", function () {
        $(this).parent().parent('tr').remove();
    });

    var _editor = UE.getEditor("edit_image",{
        initialFrameWidth:800,
        initialFrameHeight:300,
    });
    _editor.ready(function (){
        _editor.hide();
        _editor.addListener('beforeInsertImage',function(t,arg){
            var obj = _editor.queryCommandValue("serverparam");
            if(obj.type == "goods"){
                if(arg.length>5){
                    layer.msg("最多只能选择5张图片，请重新选择");
                    return false;
                }
                var getTpl = image_tpl.innerHTML
                        ,view = document.getElementById('img_preview');
                var oldHtml = $("#img_preview").html();
                if(arg.length>0) {
                    laytpl(getTpl).render(arg, function (html) {
                        view.innerHTML = oldHtml+html;
                    });
                }else{
                    layer.msg("请先上传图片");
                    return false;
                }
            }else if(obj.type == "spec"){
                if(arg.length>1){
                    layer.msg("最多只能选择1张图片，请重新选择");
                    return false;
                }
                if(arg.length>0) {
                    var specImageTd = obj.specItem.parent().find(".spec_image");
                    specImageTd.find('img').attr('src',arg[0].src);
                    specImageTd.find('input').val(arg[0].image_id);
                    specImageTd.show();
                }else{
                    layer.msg("请先选择图片");
                    return false;
                }
            }
            return true;
        });
    });
    //上传dialog
    function upImage(){
        var obj = _editor.queryCommandValue("serverparam");
        obj.type = "goods";
        var myImage = _editor.getDialog("insertimage");
        myImage.open();
    }
    /**
     * 删除图片
     * @param obj
     * @param imageId
     */
    function delImg(obj,imageId) {
        var imgDiv = $(obj).parent().parent().parent();
        imgDiv.remove();
    }
    /**
     * 设为默认图
     * @param obj
     * @param imageId
     */
    function setDefault(obj,imageId) {
        var imgDiv = $(obj).parent().parent().parent();
        $("#img_preview").prepend(imgDiv);
    }

    function croppic(obj, image_src) {
        var image = $(obj).parent().parent().parent();
        var croppicContainerModalOptions = {
            cropUrl: "{:url('images/cropper')}",
            loadPicture: image_src,
            modal: true,
            cropZoomWidth: 300,
            cropZoomHeight: 300,
            imgEyecandyOpacity: 0.4,
            loaderHtml: '<div class="loader bubblingG"><span id="bubblingG_1"></span><span id="bubblingG_2"></span><span id="bubblingG_3"></span></div> ',
            onAfterImgCrop: function (res) {
                if (res.status=='success') {
                    image.replaceWith(res.image_html);
                    layer.msg("裁剪成功");
                } else {
                    layer.msg(res.msg);
                }
                return true;
            },
            onError: function (errormessage) {
                layer.msg('onError:' + errormessage);
            }
        };
        var cropContainerModal = new Croppic('croppic', croppicContainerModalOptions);
    }

    //商品图片排序
    $('.layui-upload-list').DDSort({
        target: '.imgdiv',
        delay: 100,
        floatStyle: {
            'border': '1px solid #ccc',
            'background-color': '#fff'
        }
    });
    //上传规格图片
    $("body").on("click", ".upSpecImage", function () {
        var obj = _editor.queryCommandValue("serverparam");
        obj.type = "spec";
        obj.specItem = $(this);
        var specImage = _editor.getDialog("insertimage");
        specImage.open();
    });
    // 删除规格图片
    $("body").on("click", ".del-img", function () {
        var specImageDiv =  $(this).parent().parent();
        specImageDiv.find('img').attr('src','');
        specImageDiv.find('input').val('');
        specImageDiv.hide();
    })
</script>
<textarea id="edit_image" style="display: none;"></textarea>
